<?php

namespace app\queue\redis;

use app\api\logic\OrderLogic;
use app\model\order\Order;
use Exception;
use support\constants\LockKey;
use support\constants\QueueKey;
use support\Container;
use support\Log;
use support\service\MqClient;
use support\utils\LockUtil;
use think\facade\Db;
use Webman\Config;
use Webman\RedisQueue\Consumer;
use Yansongda\Pay\Pay;

class PaymentQuery implements Consumer
{
    // 要消费的队列名
    public $queue = QueueKey::PAYMENT_QUERY;

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    private $consumeData = [];

    // 消费
    public function consume($data)
    {
        $this->consumeData = $data;
        Db::transaction(function () use ($data) {
            $key = LockKey::ORDER_ACTION . $data['order_no'];
            $res = LockUtil::lock($key, function () use ($data) {
                $order = Order::where(['order_no' => $data['order_no']])->field([
                    'order_no',
                    'pay_status',
                    'status',
                    'pay_way',
                ])
                    ->find();
                if ($order['status'] !== Order::STATUS_WAIT_PAID || $order['pay_status'] !== Order::PAY_STATUS_WAIT) {
                    Log::info("订单[{$data['order_no']}]已支付");
                    return;
                }
                if ($order['pay_way'] == Order::PAY_WAY_ALI_PAY) {
                    $this->queryAndOperationAlipay($data['order_no']);
                }
                if ($order['pay_way'] == Order::PAY_WAY_WECHAT_PAY) {
                    $this->queryAndOperationWePay($data['order_no']);
                }

            });
            if (!$res) {
                Log::info("订单[{$data['order_no']}]支付查询操作抢锁失败");
                throw new Exception("订单[{$data['order_no']}]支付查询操作抢锁失败");
            }
        });

    }

    /**
     * 微信支付
     * @param $order_no
     */
    private function queryAndOperationWePay($order_no)
    {

    }

    /**
     * 支付宝支付
     * @param $order_no
     */
    private function queryAndOperationAlipay($order_no)
    {
        //查询支付宝订单

        //目前先h5支付
        // 1. 获取配置文件 config/payment.php
        $config = Config::get('payment');

        // 2. 初始化配置
        Pay::config($config);

        // 3. 网页支付
        $order = [
            'out_trade_no' => $order_no
        ];
        $arr = Pay::alipay()->query($order)->toArray();
        if ($arr['code'] !== "10000" || $arr['trade_status'] !== "TRADE_SUCCESS") {
            Log::info(sprintf("订单[{$order_no}]在支付宝查询订单结果异常:msg :%s sub_msg:%s", $arr['msg'], $arr['sub_msg']));
            //再次发送到队列 重试次数
            $this->consumeData['retry_num'] = ($this->consumeData['retry_num'] ?? 1) + 1;
            if ($this->consumeData['retry_num'] <= 5) {
                Container::get(MqClient::class)->send(QueueKey::PAYMENT_QUERY, $this->consumeData, $this->consumeData['retry_num'] * 60);
            }
        }else{
            //查询支付成功,处理订单后续
            $logic = new OrderLogic();
            $logic->payFinished($order_no, $arr['trade_no'], "alipay");
        }
    }
}
